package top.hmtools.wxmp.core.tools;

import java.io.Writer;
import java.util.regex.Pattern;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 * XML 与 Javabean 相互转换工具
 * @author Hybomyth
 *
 */
public class XStreamTools {
    private static String PREFIX_CDATA = "<![CDATA[";
    private static String SUFFIX_CDATA = "]]>";
    
    private static XStream xStream;
    
    /**
     * 初始化xstream，单例，纯数字不转化，其它全部转化 FIXME 实体类在有继承关系的情况下，会抽风，丢失子类属性值 20200531
     * @return
     */
    public static XStream initXStreamSingle(){
    	if(xStream == null){
    		synchronized (XStreamTools.class) {
				if(xStream == null){
					xStream = initXStream();
				}
			}
    	}
    	return xStream;
    }

    /**
     * 初始化xstream，非单例，纯数字不转化，其它全部转化
     */
    public static XStream initXStream() {
        return new XStream(new XppDriver() {
            @Override
            public HierarchicalStreamWriter createWriter(Writer out) {
                return new PrettyPrintWriter(out) {
                	@Override
                    protected void writeText(QuickWriter writer, String text) {
                    	String pattern = "[0-9\\.]+";
                    	boolean isMatch = Pattern.matches(pattern, text);
                    	if(isMatch){
                    		writer.write(text);
                    	}else{
                    		writer.write(PREFIX_CDATA + text + SUFFIX_CDATA);
                    	}
                    }
                };
            }
        });
    }

}
